<template>
  <div class="login-container">
    <div class="login-box">
      <h1 class="login-title">系统登录</h1>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="form.username"
            placeholder="请输入用户名"
            required
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="form.password"
            placeholder="请输入密码"
            required
          />
        </div>
        <button type="submit" class="login-btn" :disabled="loading">
          <span v-if="!loading">登录</span>
          <span v-else>登录中...</span>
        </button>
      </form>
      <div class="register-link">
        <router-link to="/register">还没有账户？立即注册</router-link>
      </div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import apiClient from '@/utils/api'

export default {
  name: 'LoginPage',
  setup () {
    const router = useRouter()
    const form = ref({
      username: '',
      password: ''
    })
    const loading = ref(false)
    const errorMessage = ref('')

    // 检查是否已经登录
    const checkLoginStatus = () => {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')

      if (token && userInfo) {
        // 如果存在token和用户信息，直接跳转到首页
        router.push('/home')
        return true
      }
      return false
    }

    // 组件挂载时检查登录状态
    onMounted(() => {
      checkLoginStatus()
    })

    const handleLogin = async () => {
      if (!form.value.username || !form.value.password) {
        errorMessage.value = '请输入用户名和密码'
        return
      }

      loading.value = true
      errorMessage.value = ''

      try {
        const response = await apiClient.post('/user/login', {
          username: form.value.username,
          password: form.value.password
        })

        if (response.data.code === '200') {
          // 登录成功，处理token，存储到localStorage
          const token = response.data.data.token
          localStorage.setItem('token', token)

          // 获取用户信息
          try {
            const userInfoResponse = await apiClient.get('/user/getUserInfo', {
              headers: {
                Token: token
              }
            })
            if (userInfoResponse.data.code === '200') {
              // 存储用户信息到localStorage
              localStorage.setItem('userInfo', JSON.stringify(userInfoResponse.data.data))
            }
          } catch (userInfoError) {
            console.error('获取用户信息失败:', userInfoError)
          }

          // 登录成功后建立WebSocket连接
          const { useWebsocketStore } = await import('@/store/websocket')
          const websocketStore = useWebsocketStore()
          websocketStore.connectWebSocket(token)

          // 跳转到首页
          router.push('/home')
        } else if (response.data.code === '500') {
          errorMessage.value = response.data.msg || '用户名或密码错误'
        }
      } catch (error) {
        if (error.response) {
          // 服务器返回了错误响应
          errorMessage.value = error.response.data.msg || '登录失败，请稍后重试'
        } else {
          errorMessage.value = '网络错误，请检查连接'
        }
      } finally {
        loading.value = false
      }
    }

    return {
      form,
      loading,
      errorMessage,
      handleLogin
    }
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(120deg, #f6f7f9 0%, #e7f0fd 100%);
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 2.5rem;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-title {
  margin-bottom: 1.5rem;
  color: #1890ff;
  text-align: center;
  font-size: 1.8rem;
  font-weight: 500;
}

.login-form .form-group {
  margin-bottom: 1.5rem;
  text-align: center;
}

.login-form label {
  display: block;
  margin-bottom: 0.5rem;
  color: #555555;
  font-weight: 500;
  text-align: left;
  width: 100%;
}

.login-form input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s;
  display: inline-block;
  text-align: left;
  box-sizing: border-box;
}

.login-form input:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.login-btn {
  width: 100%;
  padding: 0.75rem;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #40a9ff;
}

.login-btn:disabled {
  background-color: #a8d1ff;
  cursor: not-allowed;
}

.error-message {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  color: #ff4d4f;
  border-radius: 4px;
  text-align: center;
  font-size: 0.9rem;
}
.register-link {
  text-align: center;
  margin-top: 1rem;
}

.register-link a {
  color: #1890ff;
  text-decoration: none;
  font-size: 0.9rem;
  transition: color 0.3s;
}

.register-link a:hover {
  color: #40a9ff;
  text-decoration: underline;
}
</style>
